package com.leetcode.LeetCode精选TOP面试题;

import com.leetcode.common.utils.ArrayUtils;

/**
 * @author 覃国强
 * @date 2022-05-24 18:27
 */
public class 题库_0048_旋转图像 {

  public static void main(String[] args) {
    int[][] matrix = {{5,1,9,11},{2,4,8,10},{13,3,6,7},{15,14,12,16}};
    ArrayUtils.print2dArray(matrix);
    System.out.println("====================");
    Solution solution = new Solution();
    solution.rotate(matrix);
    ArrayUtils.print2dArray(matrix);
  }

  static
  class Solution {
    public void rotate(int[][] matrix) {
      if (matrix == null || matrix.length == 0) {
        return;
      }
//      rotateWithRotate(matrix);
      rotateWithFlip(matrix);
    }

    private void rotateWithFlip(int[][] matrix) {
      for (int i = 0; i < matrix.length / 2; ++i) {
        for (int j = 0; j < matrix.length; ++j) {
          int temp = matrix[i][j];
          matrix[i][j] = matrix[matrix.length - 1 - i][j];
          matrix[matrix.length - 1 - i][j] = temp;
        }
      }
      for (int i = 0; i < matrix.length; ++i) {
        for (int j = 0; j < i; ++j) {
          int temp = matrix[i][j];
          matrix[i][j] = matrix[j][i];
          matrix[j][i] = temp;
        }
      }
    }

    public void rotateWithRotate(int[][] matrix) {
      int si = 0;
      int sj = 0;
      int ei = matrix.length - 1;
      int ej = matrix.length - 1;

      while (si < ei) {
        for (int j = sj; j < ej; ++j) {
          int diff = j - sj;
          int temp = matrix[si][j];
          matrix[si][j] = matrix[ei - diff][sj];
          matrix[ei - diff][sj] = matrix[ei][ej - diff];
          matrix[ei][ej - diff] = matrix[si + diff][ej];
          matrix[si + diff][ej] = temp;
        }
        ++si;
        ++sj;
        --ei;
        --ej;
      }
    }
  }

}
